package com.weiaibenpao.demo.chislim.hurui.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.widget.Toast;

import com.jaeger.library.StatusBarUtil;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.hurui.httpClient.ApiClient;
import com.weiaibenpao.demo.chislim.hurui.httpClient.HHttpInterface;
import com.weiaibenpao.demo.chislim.sportoutdoor.presentation.module.PedometerApplication;
import com.weiaibenpao.demo.chislim.util.Default;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;

import static com.weiaibenpao.demo.chislim.util.Default.REQUEST_PERMISSION_CODE;

/**
 * Created by lenovo on 2017/4/10.
 */

public class HBaseActivity extends AppCompatActivity {
    private static final int PERMISSION_REQUESTCODE = 100;

    public Activity mActivity= new WeakReference<Activity>(this).get();
    public HHttpInterface apiStores = ApiClient.getModel().getService();
    private List<Call> calls;
    private Map<Integer, Runnable> allowablePermissionRunnables = new HashMap<>();
    private Map<Integer, Runnable> disallowablePermissionRunnables = new HashMap<>();

    public ProgressDialog progressDialog;
    private int checkCallPhonePermission;
    private AlertDialog dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.ku_bg), 0);
        PedometerApplication.addDestoryActivity(getClass().getName(),this
        );
    }

    public ProgressDialog showProgressDialog() {
        progressDialog = new ProgressDialog(mActivity);
        progressDialog.setMessage("加载中");
        progressDialog.show();
        return progressDialog;
    }

    public ProgressDialog showProgressDialog(CharSequence message) {
        progressDialog = new ProgressDialog(mActivity);
        progressDialog.setMessage(message);
        progressDialog.show();
        return progressDialog;
    }

    public void dismissProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            // progressDialog.hide();会导致android.view.WindowLeaked
            progressDialog.dismiss();
        }
    }



    /**
     * 权限检查
     * @param
     */
    public void checkPerMissions(){
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(mActivity, Default.MUST_PERMISSIONS,
                    REQUEST_PERMISSION_CODE);

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

        } else {
            showDialogTipUserGoToAppSettting();
        }
    }

    // 提示用户去应用设置界面手动开启权限
            private void showDialogTipUserGoToAppSettting() {

                dialog = new AlertDialog.Builder(this)
                       .setTitle("定位权限不可用")
                        .setMessage("请在-应用设置-权限-中，允许东极圈使用定位权限确保跑步功能的正常使用")
                      .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                                         // 跳转到应用设置界面
                                         goToAppSetting();
                                     }
                 })
                         .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                     @Override
                     public void onClick(DialogInterface dialog, int which) {
                         finish();
                         Toast.makeText(mActivity, "请在应用管理中打开相关访问权限，确保该功能的正常使用", Toast.LENGTH_SHORT).show();
                                     }
                 }).setCancelable(false).show();
             }
    // 跳转到当前应用的设置界面
     private void goToAppSetting() {
                 Intent intent = new Intent();

                 intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                 Uri uri = Uri.fromParts("package", getPackageName(), null);
                 intent.setData(uri);

                 startActivityForResult(intent, 123);
             }
    @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                 super.onActivityResult(requestCode, resultCode, data);
                 if (requestCode == 123) {

                         if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                 // 检查该权限是否已经获取
                                 int i = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
                                 // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                                 if (i != PackageManager.PERMISSION_GRANTED) {
                                         // 提示用户应该去应用设置界面手动开启权限
                                         showDialogTipUserGoToAppSettting();
                                     } else {
                                         if (dialog != null && dialog.isShowing()) {
                                                 dialog.dismiss();
                                             }

                                     }
                             }
                     }
             }

    @Override
    protected void onDestroy() {
        callCancel();
//        System.exit(0);

        super.onDestroy();
    }

    public void addCalls(Call call) {
        if (calls == null) {
            calls = new ArrayList<>();
        }
        calls.add(call);
    }

    private void callCancel() {
        if (calls != null && calls.size() > 0) {
            for (Call call : calls) {
                if (!call.isCanceled())
                    call.cancel();
            }
            calls.clear();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        return super.onKeyDown(keyCode, event);
    }


}
